package com.example.benefitcommunity.util;


import com.example.benefitcommunity.entity.BcUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author makejava
 */
public class JWTUtil {
    /**
     * 过期时间为一周
     */
    private static final long EXPIRE = 60000 * 60 * 24 * 7;
    /**
     * 密钥
     */
    private static final String SECRET = "xdclass.net168";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PRE_FIX = "xdclass";
    /**
     * subject主题
     */
    private static final String SUBJECT = "xdclass";

    /**
     * 获取token
     */
    public static String token(BcUser user) {
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("id", user.getId())
                .claim("username", user.getUsername())
                .claim("password", user.getPassword())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PRE_FIX + token;
        return token;
    }

    /**
     * 解密
     */
    public static Claims checkJWT(String token) {
        // 添加空值检查
        if (token == null || token.isEmpty()) {
            return null;
        }

        try {
            return Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PRE_FIX, ""))
                    .getBody();
        } catch (Exception e) {
            // 解析失败时返回null
            return null;
        }
    }
}
